import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from '@/api'
import { setToken, getToken, removeToken } from '@/utils/token'

const state = {
    code: '',
    token: getToken(),
    userInfo: {}
}
const actions = {
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit('GETCODE', result.data)
        }
    },
    // 完成注册
    userRegister({ commit }, user) {
        let result = reqUserRegister(user)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('用户名已注册'))
        }
    },
    // 登录请求,成功后会返回一个token
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
            setToken(result.data.token)
            // 未登录会出错,所以不写else了
        }
    },
    // 获取用户信息
    async userInfo({ commit }) {
        let result = await reqUserInfo()
        if (result.code == 200) {
            commit('USERINFO', result.data)
            // 未登录会出错,所以不写else了
        }
    },
    // 退出登录
    async userLogout({ commit }) {
        let result = await reqLogout()
        if (result.code == 200) {
            commit('USERLOGOUT')
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    // 设置token
    USERLOGIN(state, token) {
        state.token = token
    },
    // 获取用户信息
    USERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    // 退出登录
    USERLOGOUT(state) {
        // 清空信息
        state.token = '',
            state.userInfo = {},
            removeToken()
    }
}
const getters = {}

export default {
    state,
    actions,
    mutations,
    getters
}